<?php
/**
 *                          _ooOoo_
 *                         o8888888o
 *                         88" . "88
 *                         (| -_- |)
 *                         O\  =  /O
 *                      ____/`---'\____
 *                    .'  \|     |//  `.
 *                   /  \|||  :  |||//  \
 *                  /  _||||| -:- |||||-  \
 *                  |   | \\  -  /// |   |
 *                  | \_|  ''\---/''  |   |
 *                  \  .-\__  `-`  ___/-. /
 *                ___`. .'  /--.--\  `. . __
 *             ."" '<  `.___\_<|>_/___.'  >'"".
 *            | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *            \  \ `-.   \_ __\ /__ _/   .-` /  /
 *       ======`-.____`-.___\_____/___.-`____.-'======
 *                          `=---='
 *
 *==================================================
 *                  佛祖保佑        永无BUG
 *         佛曰:
 *                写字楼里写字间，写字间里程序员；
 *                程序人员写程序，又拿程序换酒钱。
 *                酒醒只在网上坐，酒醉还来网下眠；
 *                酒醉酒醒日复日，网上网下年复年。
 *                但愿老死电脑间，不愿鞠躬老板前；
 *                奔驰宝马贵者趣，公交自行程序员。
 *                别人笑我忒疯癫，我笑自己命太贱；
 *                不见满街漂亮妹，哪个归得程序员？
 *==================================================
 */

 
/**
 * 大营配置
 * @author  Don
 * @date    2019-05-22
 */

namespace App\Admin\Controllers\kly;

use App\Models\kly\Kly_camp;
use App\Models\kly\Kly_student;
use App\Models\Squad;
use App\Models\Student;
use DB;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
// use Encore\Admin\Grid\Displayers\Modal;


class Small_camp_configController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use($request){

            $content->header('小营');
            $content->description('配置');
            
            $content->body($this->grid($request)->render());
            $content->body($this->add_stu_to_camp_form());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('小营');
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('小营');
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(Request $request)
    {
        return Admin::grid(Kly_camp::class, function (Grid $grid) use($request){
            if (!is_null($request['pid'])) {
                $grid->model()->where('pid',$request['pid']);
            }else
            {
                $grid->model()->where('camp_type','2');
            }
            if (!Admin::user()->isAdministrator()) {
                $grid->model()->where('camp_type','2')->where(function($query){$query->WhereRaw('find_in_set('.Admin::user()->id.',`leaders`)')->orWhereRaw('find_in_set('.Admin::user()->id.',`tutors`)');});
            }
            
            $grid->model()->orderBy('id', 'desc');
            // $grid->id(trans('admin.ID'))->sortable();
            $grid->name(trans('admin.name'));
            $grid->column('所属大营')->display(function(){
                return Kly_camp::where('id',$this->pid)->value('name');
            });
            // $grid->squads('覆盖班级')->display(function($squads){
            //     $squads_arr = [];
            //     foreach ($this->squads as  $sv) {
            //         array_push($squads_arr,Squad::where('id',$sv)->value('name'));
            //     }
            //     return $squads_arr;
            // })->label('danger')->style('max-width:600px;word-break:break-all;');
            
            
            $grid->teachers('老师')->display(function($teachers){
                $teachers_arr = [];
                foreach ($this->teachers as  $tev) {
                    array_push($teachers_arr,DB::table('admin_users')->where('id',$tev)->value('username'));
                }
                return $teachers_arr;
            })->label('primary')->style('max-width:600px;word-break:break-all;');
            
			$grid->tutors('主要班主任')->display(function($tutors){
			    return DB::table('admin_users')->where('id',$this->tutors)->value('username');
			})->label('success');
            
            $grid->aids('助理班主任')->display(function($aids){
                $aids_arr = [];
                foreach ($this->aids as  $tv) {
                    array_push($aids_arr,DB::table('admin_users')->where('id',$tv)->value('username'));
                }
                return $aids_arr;
            })->label('success');
            $grid->column('分组数')->display(function(){
                $camp_group_count = Kly_camp::where('pid',$this->id)->count();
                return '<a style="cursor:pointer;" href="camp_group_config?pid='.$this->id.'">'.$camp_group_count."</a>";
            });
            $grid->column('人数')->display(function(){
                $students = Kly_student::where('small_camp_id',$this->id)->count();
                return '<a style="cursor:pointer;" href="kly_student_list?s_id='.$this->id.'">'.$students."</a>";
            });
            $grid->actions(function ($actions) {
                $actions->disableView();
				$actions->disableDelete();
				$actions->disableEdit();
                $camp_info = $actions->row;
                $selected_students = implode(',',Kly_student::where(['big_camp_id'=>$camp_info->pid,'small_camp_id'=>$camp_info->id])->pluck('student_id')->toArray());
                if(Admin::user()->isAdministrator()){
                    $actions->prepend('<a data-toggle="modal" data-target="#myModal" data-campid="'.$actions->getKey().'" data-students="'.$selected_students.'"><i class="fa fa-user-plus"></i></a>');
                }
            });

            //禁用导出按钮
            $grid->disableExport();
            //禁用筛选按钮
            $grid->disableFilter();

            $grid->tools(function ($tools) { 
                //关闭批量删除 
                $tools->batch(function ($batch) { 
                    $batch->disableDelete(); 
                });
            });
        });
    }

    protected function add_stu_to_camp_form()
    {
        return view('admin.kly.add_stu_to_camp_form');
    }

    protected function get_camp_stus(Request $request)
    {
        $camp_id = $request['camp_id'];
        $big_camp_id = Kly_camp::where('id',$camp_id)->value('pid');
        $big_camp_squads = Kly_camp::where('id',$big_camp_id)->value('squads');
        $all_studentIds = Student::whereIn('squad_id',$big_camp_squads)->where('status','1')->pluck('id')->toArray();
        $current_camp_done_assign_stuIds = Kly_student::where('small_camp_id',$camp_id)->pluck('student_id')->toArray();
        $all_done_assign_stuIds = Kly_student::all()->pluck('student_id')->toArray();
        //如果对应小营已分配学生，则候选列表中显示所有待分配的和当前小营分配的学生集合
        if (count($all_done_assign_stuIds)>0) {
            if (count($current_camp_done_assign_stuIds)>0) {
                $can_assign_stuIds = array_merge(array_diff($all_studentIds,$all_done_assign_stuIds),$current_camp_done_assign_stuIds);
            }else{
                $can_assign_stuIds = array_diff($all_studentIds,$all_done_assign_stuIds); 
            }
        }else{
            $can_assign_stuIds = $all_studentIds;
        }
        $students = DB::table('students as stu')->join('squads as s',function($join){
            $join->on('stu.squad_id','=','s.id');
        })->whereIn('stu.id',$can_assign_stuIds)->where('stu.status','=','1')->orderBy('s.name')->select('stu.id as studentId',DB::raw("concat(stu.ch_name,' - ',stu.en_name,'(',s.name,')') as studentName"))->get();
        $arr=array();
        foreach($students as $k => $v){
            $arr[] = array('id'=>$v->studentId,'text'=>$v->studentName);
        }
        return $arr;
    }

    protected function save_camp_students(Request $request)
    {
        $camp_students = $request['students'];
        // dd($camp_students);
        $small_camp_id = $request['camp_id'];
        $b_camp_id = Kly_camp::where('id',$small_camp_id)->value('pid');
		$small_camp_students = Kly_student::where(['big_camp_id'=>$b_camp_id,'small_camp_id'=>$small_camp_id])->pluck('student_id')->toArray();
		if(count($small_camp_students)>0){
			$diff_students1 = array_diff($camp_students,$small_camp_students);
			$diff_students2 = array_diff($small_camp_students,$camp_students);
			if(!is_null($diff_students1))
			{
				//加了学员
				foreach($diff_students1 as $v)
				{
					$data = [
						'student_id' => $v,
						'big_camp_id' => $b_camp_id,
						'small_camp_id' => $small_camp_id,
						'camp_group_id' => '0',
						'is_chargeman' => '0'
					];
					Kly_student::insert($data);
				}
			}
			if(!is_null($diff_students2)){
				foreach($diff_students2 as $v){
					//如果删减的不是小组长,那么直接删减,是则不删除
					if(Kly_student::where('student_id',$v)->value('is_chargeman')==0){
						Kly_student::where('student_id',$v)->delete();
					}
				}
			}
		}else{
			foreach($camp_students as $v)
			{
				$data = [
					'student_id' => $v,
					'big_camp_id' => $b_camp_id,
					'small_camp_id' => $small_camp_id,
					'camp_group_id' => '0',
					'is_chargeman' => '0'
				];
				Kly_student::insert($data);
			}
		}
		
        //查询出对应小营的学生名单
  //       $kly_students = Kly_student::where(['big_camp_id'=>$b_camp_id,'small_camp_id'=>$small_camp_id])->count();
		// 
  //       if ($kly_students>0) {
  //           Kly_student::where(['small_camp_id'=>$small_camp_id,'big_camp_id'=>$b_camp_id,'is_chargeman'=>0])->delete();
  //       }
  //       foreach ($camp_students as $value) {
		// 	$data = [
		// 		'student_id' => $value,
		// 		'big_camp_id' => $b_camp_id,
		// 		'small_camp_id' => $small_camp_id,
		// 		'camp_group_id' => '0',
		// 		'is_chargeman' => '0'
		// 	];
		// 	Kly_student::insert($data);
  //           
  //       }
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Kly_camp::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('name','名称')->rules('required')->rules('required')->addElementLabelClass('must-input');
            $form->hidden('camp_type')->value('2');
			if(Admin::user()->isAdministrator()){
				$pid_options = Kly_camp::where('camp_type','1')->pluck('name','id');
			}else{
				$pid_options = Kly_camp::where('camp_type','1')->WhereRaw('find_in_set('.Admin::user()->id.',`leaders`)')->pluck('name','id');
			}
			
            $form->select('pid','所属大营')->options($pid_options)->rules('required')->addElementLabelClass('must-input');
            //$form->listbox('students','分配学员');
            $all_admin_users = DB::table('admin_users')->pluck('username','id');
            //$form->multipleSelect('leaders', '主负责人')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            $form->multipleSelect('teachers', '老师')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            $form->select('tutors', '主要班主任')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
            $form->multipleSelect('aids', '助理班主任')->options($all_admin_users)->rules('required')->addElementLabelClass('must-input');
			$form->saved(function (Form $form) {
                $camp = Kly_camp::find($form->model()->id);
				$camp_leaders = Kly_camp::where('id',$form->pid)->value('leaders');
                $camp_squads = Kly_camp::where('id',$form->pid)->value('squads');
                $camp_term = Kly_camp::where('id',$form->pid)->value('term_id');
				$camp->leaders = $camp_leaders;
                $camp->squads = $camp_squads;
                $camp->term_id = $camp_term;
                $camp->save();
				
				//大营负责人配置好小营后,给当前小营的主要班主任分配角色"苦令营小营班主任->kly_tutor"
				//当前小营的主要班主任
				$tutor = $form->tutors;
				
				//找出角色为"苦令营小营班主任"的角色ID
				$role_id = DB::table('admin_roles')->where('slug','kly_tutor')->value('id');
				//判断主负责人是否已有此角色,有则不分配,无则分配
				if(DB::table('admin_role_users')->where(['role_id'=>$role_id,'user_id'=>$tutor])->count()==0)
				{
					//给主要班主任分配角色
					DB::table('admin_role_users')->insert([
						'role_id' => $role_id,
						'user_id' => $tutor
					]);
				}
            });
            //去掉添加/编辑表单的重置按钮
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }
}